<?
// +----------------------------------------------------------------------
// | ThinkCt框架[基于ThinkPHP6.0开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2021 http://www.thinkct.net
// +----------------------------------------------------------------------
// | ThinkCt承诺基础框架商业版永久免费技术支持，您可用于学习和商用，但必须保留软件版权信息。
// +----------------------------------------------------------------------
// | Author: 时光网络 <66983239@qq.com>，开发者QQ群：61162800 付费QQ群：250059867
// +----------------------------------------------------------------------
use think\Db;
use think\Request;
use app\common\library\Update;

// 入库表
function intotable($itable,$zdarr,$resarr){
	$sql   = "insert into ".$itable."(".$zdarr.")values(".$resarr.")";
	$query = Db::query($sql);
	return $query;
}

// 更新表
function updatetable($utable,$ures,$uwhere=""){
	$sql   = "update ".$utable." set ".$ures." ".$uwhere;
	$query = Db::query($sql);
	return $query;
}

// 删除表
function deletetable($dsql){
	$sql   = "delete from ".$dsql;
	$query = Db::query($sql);
	return $query;
}

function adnum($type){
	$sj  = sj();
	$ads = Db::name('ads')->where(['type1'=>1,'type2'=>$type])->find();
	if($ads){
		//获取目标广告信息 若存在则执行
		$tg = Db::query("select count(*) as id from shop_tuiguang where ads='".$type."' and dsj>'".$sj."' and zt=1")[0];	
		//exit(var_dump($tg));
		//计算已展示中目标广告数
		if(($ads['adnum']-$tg['id'])<=0){
			//id是已展示广告数 、adnum是允许的广告数
			return 0;
			//没空位
		}else{
			return ($ads['adnum']-$tg['id']);
			//有空位 返回空位数
		}
	}
}

$auth = Update::auth();

// 更新会员信誉
function uprev($sell,$buy){
	if($buy!=''){
		// 买家信誉总值
		$rowb = Db::name('reviews')->where([
			'buy'     => $buy,
			'buyimp'  => ['>',0],
			'sellimp' => ['>',0]
		])->sum('sellimp');
		Db::name('buy')->where('bh',$buy)->update(['rev_m'=>$rowb]);
	}
	if($sell!=''){
		//卖家
		//$results=mysql_query("select sum(Attitude),sum(efficiency),sum(quality),count(*),sum(buyimp),sum(case when buyimp=0 then 1 else 0 end),sum(case when buyimp=-1 then 1 else 0 end),sum(case when buyimp>0 and buytime > DATE_SUB(NOW(),INTERVAL 1 month) then 1 else 0 end),sum(case when buyimp=0 and buytime > DATE_SUB(NOW(),INTERVAL 1 month) then 1 else 0 end),sum(case when buyimp<0 and buytime > DATE_SUB(NOW(),INTERVAL 1 month) then 1 else 0 end),sum(case when buyimp>0 and buytime > DATE_SUB(NOW(),INTERVAL 3 month) then 1 else 0 end),sum(case when buyimp=0 and buytime > DATE_SUB(NOW(),INTERVAL 3 month) then 1 else 0 end),sum(case when buyimp<0 and buytime > DATE_SUB(NOW(),INTERVAL 3 month) then 1 else 0 end),sum(case when buyimp>0 and buytime > DATE_SUB(NOW(),INTERVAL 6 month) then 1 else 0 end),sum(case when buyimp=0 and buytime > DATE_SUB(NOW(),INTERVAL 6 month) then 1 else 0 end),sum(case when buyimp<0 and buytime > DATE_SUB(NOW(),INTERVAL 6 month) then 1 else 0 end),sum(case when buyimp>0 and buytime < DATE_SUB(NOW(),INTERVAL 6 month) then 1 else 0 end),sum(case when buyimp=0 and buytime < DATE_SUB(NOW(),INTERVAL 6 month) then 1 else 0 end),sum(case when buyimp<0 and buytime < DATE_SUB(NOW(),INTERVAL 6 month) then 1 else 0 end) from shop_reviews where sell='".$sell."' and buyimp!='' and sellimp!=''");
		//$rows = mysql_fetch_row($results);
		$sql = "select sum(Attitude),sum(efficiency),sum(quality),count(*),sum(buyimp),sum(case when buyimp=0 then 1 else 0 end),sum(case when buyimp=-1 then 1 else 0 end),sum(case when buyimp>0 and buytime > DATE_SUB(NOW(),INTERVAL 1 month) then 1 else 0 end),sum(case when buyimp=0 and buytime > DATE_SUB(NOW(),INTERVAL 1 month) then 1 else 0 end),sum(case when buyimp<0 and buytime > DATE_SUB(NOW(),INTERVAL 1 month) then 1 else 0 end),sum(case when buyimp>0 and buytime > DATE_SUB(NOW(),INTERVAL 3 month) then 1 else 0 end),sum(case when buyimp=0 and buytime > DATE_SUB(NOW(),INTERVAL 3 month) then 1 else 0 end),sum(case when buyimp<0 and buytime > DATE_SUB(NOW(),INTERVAL 3 month) then 1 else 0 end),sum(case when buyimp>0 and buytime > DATE_SUB(NOW(),INTERVAL 6 month) then 1 else 0 end),sum(case when buyimp=0 and buytime > DATE_SUB(NOW(),INTERVAL 6 month) then 1 else 0 end),sum(case when buyimp<0 and buytime > DATE_SUB(NOW(),INTERVAL 6 month) then 1 else 0 end),sum(case when buyimp>0 and buytime < DATE_SUB(NOW(),INTERVAL 6 month) then 1 else 0 end),sum(case when buyimp=0 and buytime < DATE_SUB(NOW(),INTERVAL 6 month) then 1 else 0 end),sum(case when buyimp<0 and buytime < DATE_SUB(NOW(),INTERVAL 6 month) then 1 else 0 end) from shop_reviews where sell='".$sell."' and buyimp!='' and sellimp!=''";
		$query = Db::query($sql);
		//0.态度 1.效率 2.质量 3.总数 4.信誉总值 5.中评数 6.差评数 7.1月内好评 8.1月内中评  9.1月内差评  10.3月内好评 11.3月内中评  12.3月内差评 13.6月内好评 14.6月内中评 15.6月内差评 17.6月前好评 18.6月前中评 19.6月前差评
		foreach($query[0] as $k => $v){
			$rows[] = $v;
		}		
		$return = $rows[3];
		//总数
		for ($i=0;$i<3; $i++){
			//循环计算开始
			if($rows[3]>0){
				//有评分则执行
				$return.="|".number_format($rows[$i]/$rows[3],2);
			} else {
				//有评分则默认5分
				$return.="|5";
			}
		}
		//循环计算结束
		$goods=$rows[3]-($rows[5]+$rows[6]);
		//好评=总评数-中差评
		$return.="|".$goods."|".$rows[5]."|".$rows[6]."|".$rows[7]."|".$rows[8]."|".$rows[9]."|".$rows[10]."|".$rows[11]."|".$rows[12]."|".$rows[13]."|".$rows[14]."|".$rows[15]."|".$rows[16]."|".$rows[17]."|".$rows[18];
		Db::name('sell')->where('bh',$sell)->update(['score'=>$return,'rev_m'=>$rows[4]]);
	}
}

// 判断余额是否充足
function panduanmoney($m,$u){
	$row1 = Db::name('user')->where('bh',$u)->find();
	$money = $row1['money'];
	if($m>$money){
		echo "<script>";
		echo "alert('抱歉，您的账户余额不足，请重新下单购买！');parent.location.href='/member/cart/';";
		echo "</script>";
		exit;
	}
}

// 参数调用结束
function fees($c_money,$c_type,$c_Role){
	/*手续费*/
	$jyfees = '0.03';
	$fees=round($c_money*$jyfees,2);
	//单方支付中介费
	if($c_type=='aa'){
		//AA制（平摊）
		$fees=round($fees/2,2);
	} elseif($c_type!=$c_Role){
		$fees=0;
	}
	return $fees;
}

// 会员积分值变更、追踪
function PointUpdatejf($c_ubh,$c_tit,$c_jf,$c_pro=null,$etime=null){
	$sj=date('Y-m-d H:i:s');
	if($etime!=''){
		$sj=$etime;
	}
	// 用于自动执行交易
	Db::name('user')->where('bh',$c_ubh)->setInc('jifen',$c_jf);
	Db::name('jifen')->insert([
		'bh'  => time(),
		'ubh' => $c_ubh,
		'tit' => $c_tit,
		'jf'  => $c_jf,
		'sj'  => $sj,
		'uip' => uip(),
		'pro' => $c_pro	
	]);	
}
// 会员金额值变更
function PointUpdate($c_ubh,$c_money,$c_tit,$c_pro=null,$c_fees=null,$etime=null){
	$sj=date('Y-m-d H:i:s');
	if($etime!=''){
		$sj=$etime;
	}
	//用于自动执行交易
	$mbh = time();
	Db::name('user')->where('bh',$c_ubh)->setInc('money',$c_money);
	
	Db::name('moneyrecord')->insert([
		'bh' => $mbh,
		'ubh' => $c_ubh,
		'tit' => $c_tit,
		'moneynum' => $c_money,
		'sj' => $sj,
		'uip' => $_SERVER['REMOTE_ADDR'],
		'pro' => $c_pro	
	]);
	
	if($c_fees > 0){
		//判断是否含有手续费
		Db::name('user')->where('bh',$c_ubh)->setDec('money',$c_fees);
		
		Db::name('moneyrecord')->insert([
			'bh' => $mbh,
			'ubh' => $c_ubh,
			'tit' => '交易手续费',
			'moneynum' => '-'.$c_fees,
			'sj' => $sj,
			'uip' => $_SERVER['REMOTE_ADDR'],
			'pro' => $c_pro	
		]);
	}
}

// 交易自处理
function e_order($ddbh,$cz,$etime,$adminbz = null){

	$order = Db::name('down')->where(['ddbh'=>$ddbh,'buy|sell'=>session('usercode')])->find();
	$ddzt = $order['ddzt'];
	//订单状态
	if($ddzt == 'db' || $ddzt == 'back' || $ddzt == 'backerr'){
		//状态必须为交易中、退款中、拒绝退款才能执行
		$goodbh = $order['codebh'];
		//商品编号
		$c_money = $order['money1'];
		//纯交易额（含抵价和手续费）
		$z_money = $order ['money1'];
		//纯交易额（含抵价和手续费）
		if($order['type'] == 'custom' || $order['type'] == 'task'){
			$z_money = $order['money2'];
			//如果是任务或自助则入款为money2，因为money1可能有手续费
		}
		$jifen = $order['jf'];
		//使用积分
		$sell = $order['sell'];
		//卖家
		$buy = $order['buy'];
		//买家
		$tyname = typename($order['type']);
		// 金额
		$money = $order['money1'];
		//类型名
		if($cz == 'success'){
			// 执行成交
			Db::name('moneydb')->where(['sell'=>$sell,'buy'=>$buy,'ddbh'=>$ddbh])->delete();
			// 删除担保交易
			Db::name('moneyback')->where(['sell'=>$sell,'buy'=>$buy,'ddbh'=>$ddbh])->delete();
			// 删除退款交易、以防是退款是取消退款的操作
			Db::name('down')->where(['sell'=>$sell,'buy'=>$buy,'ddbh'=>$ddbh])->update(['ddzt'=>'success','etime'=>$etime]);
			// 修改交易状态
			Db::name('sell')->where('bh',$sell)->setInc(['sale_n'=>1,'sale_m'=>$money]);
			//卖家交易额、笔数增加
			PointUpdatejf($buy,"购物消费获赠".round($z_money,0)."积分",round($z_money,0),$goodbh,$etime);
			if($jifen>0 && $order[type]=='code'){
				// 若有用积分且为源码则执行加分
				PointUpdatejf($sell,"获得买家抵价".$jifen."积分",$jifen,$goodbh,$etime);
			}
			//加分结束
			$sfees = fees($z_money,$order['fees'],'sell');
			//卖家手续费
			PointUpdate($sell,$z_money,"交易成功(".$tyname.")",$goodbh,$sfees,$etime);
			//支付给卖家
		}elseif($cz == 'backsuc' || $cz == 'forback'){
			// 判断是否为部分退款
			if($order['backmoney'] != 0){
				$c_money = $order['backmoney'];
			}
			//执行退款
			Db::name('moneydb')->where(['sell'=>$sell,'buy'=>$buy,'ddbh'=>$ddbh])->delete();
			//删除担保交易
			Db::name('moneyback')->where(['sell'=>$sell,'buy'=>$buy,'ddbh'=>$ddbh])->delete();
			//删除退款交易
			Db::name('down')->where(['sell'=>$sell,'buy'=>$buy,'ddbh'=>$ddbh])->update(['ddzt'=>$cz,'adminbz'=>$adminbz,'etime'=>$etime]);			
			//修改交易状态
			PointUpdate($buy,$c_money,"退款成功(".$tyname.")",$goodbh,'',$etime);
			//退款给买家
			PointUpdatejf($buy,"退款成功,返还".$jifen."积分",$jifen,$goodbh,$etime);
		}
	}
}

// 评论
function eva($num){
	if($num=="2"){
		//好评
		$eva="good";
	}elseif($num=="0"){	
	    //中评
		$eva="normal";
	}elseif($num=="-1"){	
	    //差评
		$eva="bad";	   	
	}	
	return $eva;
}

// ip地址
function uip(){
	return $_SERVER["REMOTE_ADDR"];
}
// 时间
function sj($sj=null,$day=1){
	if(!empty($sj)){
		$data = strtotime("{$day} day",strtotime($sj));
		$date = date('Y-m-d H:i:s',$data);
		return $date;
	}
	return date('Y-m-d H:i:s');
}

// 写入登陆
function anquan($u,$t,$f){
	$uip = $_SERVER["REMOTE_ADDR"];
	$sj = date('Y-m-d H:i:s');
	if(!empty($uip)){
		$ip_info=get_ip_city($uip);
	}else{
		$ip_info='未知地区';
	}	
	if(isset($_SESSION['TZPCWAP'])){
		$pc = '手机端';
	}else{
		$pc = '电脑端';
	}		
	/*登陆记录*/
	Db::name('anquan')->insert([
		'ubh' => $u,
		'uip' => $uip,
		'type' => $t,
		'way' => $f,
		'sj' => $sj,
		'city' => $ip_info,
		'pc' => $pc 	
	]);
}

// 获取用户信息 $u=编号 $r=查询字段 $t=用户类型 $f=附加值
function user($u,$r,$t,$f = null){
	
	$return = null;
	$user = Db::name('user')->where('bh',$u)->find();
	//通用信息
	if($t=='sell' || $t=='buy'){
		$row = Db::name($t)->where('bh',$u)->find();
		//用户类型信息
	}
	$row['jifen'] = null;
	$arr=explode("|",$r);
	//可能有多个字段查询
	for ($i=0;$i<count($arr); $i++){
		switch($arr[$i]){
			case "qq": //联系QQ
			$return.=kefu($t,$row['contact'],$row['tx'],$row['name'],"qq-".$f);
			break;
			case "cqq": //联系QQ
			if($t=='buy'){
				$return.=$row['contact'];
			} else {
				preg_match_all('/<qq-'.$f.'>([^<>]+)<\/qq-'.$f.'>/',$row[contact],$data_result);
				//提取
				if($data_result[1][0]==''){
					//没有指定场景客服
					$type=explode("-",$ts);
					preg_match_all('/<qq-i>([^<>]+)<\/qq-i>/',$row[contact],$data_result);
					//提取全局
				}
				$result=explode("|",$data_result[1][0]);
				for ($q=0;$q<=count($result); $q++){
					if($result[$q]!=''){
						if(strstr($result[$q],":")){
							//含职位
							$ep[$q]=explode(":",$result[$q]);
							if($q+1<count($result)){
								$ep[$q][0].=",";
							}
							$return.=$ep[$q][0];
						}
					}
				}
			}
			break;
			case "tx"://头像
			if($row['tx']!=''){
				$tp=$row['tx'];
			} else {
				$tp="none.jpg";
			}
			$return.="".$tp;
			break;
			case "name"://名称
			case "cname"://名称
			if(strlen($row['name'])>14){
				$row['name'] = changdu($row['name'],30);
			}
			if($t=='sell' && $arr[$i]=='name'){
				//卖家名称
				$return.="<a href='/ishop".$row['id']."/' target=_blank>".$row['name']."</a>";
			} else {
				//买家名称
				$return.=$row['name'];
			}
			break;
			case "aqmsc": //根据用户信息生成安全码 限于user表
			$t.=$user['sj'].$user['uip'];
			$pw=md5($t);
			$okpw=substr($pw,7,20);
			$return.=$okpw;
			break;
			case "money": //获取用户余额 限于user表
			$return.=number_format($user[money],2,'.','');
			break;
			case "xy": //获取信誉值 
			$return.=$row['rev_m'];
			break;
			case "sid": //获取卖家ID
			$return.=$row['id'];
			break;
			case "rz": //获取认证情况
			if($user['email_zt']==1){
				$return.="<i title='已通过邮箱验证'></i>";
			}
			if($user['phone_zt']==1){
				$return.="<i class='mob' class='已通过手机认证'></i>";
			}
			break;
			default://通用信息
			$tinfo=$user[$arr[$i]];
			if($tinfo==''){
				$tinfo=$row[$arr[$i]];
			}
			$return.=$tinfo;
			break;
		}
		if($i+1<count($arr)){
			$return.="||";
		}
	}
	return $return;
}

// 评价自处理
function e_rev(){
	$query = Db::query("select ddbh,codebh,buy,sell,type,etime from shop_down where  DATE_SUB(NOW(),INTERVAL 3 DAY) > etime and ddzt='success' and rev_zt<2 and (buy='".session('usercode')."' or sell='".session('usercode')."')");
	//exit(var_dump($query));
	foreach($query as $order){
		$ddbh  = $order['ddbh'];
		// 查询是否存在交易完成超过3天且没有均评价
		$ptime = date("Y-m-d H:i:s",strtotime("+3 day",strtotime($order['etime'])));
		// 评价时间=结束时间+3天
		$rev   = Db::name('reviews')->where('ddbh',$ddbh)->find();
		if($rev){
			//存在 有一方评价
			if($rev["buyimp"]==''){
				//买家未评
				$ses = ['buytime'=>$ptime,'buyimp'=>2,'Attitude'=>5,'efficiency'=>5];
			}else{
				//卖家未评
				$ses = ['selltime'=>$ptime,'sellimp'=>2];
			}
			Db::name('reviews')->where('ddbh',$order['ddbh'])->update($ses);
			//更新评价表
		}else{
			//不存在 双方都没评价，新建
			Db::name('reviews')->insert([
				'ddbh'       => $order['ddbh'],
				'pro' 		 => $order['codebh'],
				'type'		 => $order['type'],
				'buy' 		 => $order['buy'],
				'sell'       => $order['sell'],
				'buyimp'     => 2,
				'sellimp'    => 2,
				'Attitude'   => 5,
				'efficiency' => 5,
				'quality'    => 5,
				'buytime'    => $ptime,
				'selltime'   => $ptime,
				'zt'         => 1			
			]);		
		}
		Db::name('down')->where('ddbh',$order['ddbh'])->update(['rev_zt'=>2]);
		//修改评价状态
		uprev($order['sell'],$order['buy']);
		//更新卖分评价值
	}
}

// 增加用户余额
function update_money($ubh, $number, $tit ,$pro = null){
	// 更新用户积分
	Db::name('user')->where('bh',$ubh)->setInc('money',$number);
	// 写入积分记录
	Db::name('moneyrecord')->insert([
		'bh' => shop_bh(),
		'ubh' => $ubh,
		'tit' => $tit,
		'moneynum' => $number,
		'sj' => date('Y-m-d H:i:s'),
		'uip' => $_SERVER["REMOTE_ADDR"],
		'pro' => $pro	
	]);
}



// 增加用户积分
function update_jifen($ubh, $number, $tit ,$pro = null){
	// 更新用户积分
	Db::name('user')->where('bh',$ubh)->setInc('jifen',$number);
	// 写入积分记录
	Db::name('jifen')->insert([
		'bh' => shop_bh(),
		'ubh' => $ubh,
		'tit' => $tit,
		'jf' => $number,
		'sj' => date('Y-m-d H:i:s'),
		'uip' => $_SERVER["REMOTE_ADDR"],
		'pro' => $pro	
	]);
}

// 登陆查询
function anquaninfo($u,$r,$n){
	
	//$anquan_count = Db::name('anquan')->where(['ubh'=>$u])->count();
	//if($anquan_count >= 2){
		//$ses=" order by id desc limit ".$n.",1";
	//}	
	$row = Db::name('anquan')->where('ubh',$u)->order('id desc')->find();
	if($row){
		return $row[$r];
	} else {
		return "-";
	}
}

// 获取商品属性 //获取商品附加选项
function spsx($t1,$t2="1",$name = null){
	if($t2=="1"or$t2=="typename"){
		$row = Db::name('type')->where('id',$t1)->find();
		if($row){
			if($t2=="typename"){
				return $row['typename'];
			}else{
				return $row['name2'];
			}			
		}else{
			return "无";
		}		
	}else{
		$arr_slideshow = explode("|",$t1.'|');$j=1;
		$str = null;
		foreach($arr_slideshow as $value){
			//$sql='select * from shop_type where admin=2 and id="'.$value.'"';
			$row = Db::name('type')->where('id',$value)->find();
			if($row['name1']==$name and !empty($row['name1'])){
				$str=$str.$row['name2']."，";
			}	
		}//循环结束
		$strend=trim($str,'，');//去除最后个逗号
		if(empty($strend)){
			return "无";
		}else{
			return $strend;
		}		
	}	
}

// 获取商品图片
function get_tp($bh, $type="tp") {
	if($type == 'tp') {
		$where = ['admin'=>1];
	}
    $data = Db::name('file')->where(['bh'=>$bh])->where($where)->find();
	if(!$data){
		$where = ['admin'=>2];
		$data  = Db::name('file')->where(['bh'=>$bh])->where($where)->find();
	}
    return $data['url'];
}

// 获取评分
function reviews_imp($filter){
	switch($filter){
		case "q"://全部评价
	    return "buyimp='-1'";
	    break;		
		case "2"://好评
	    return "buyimp='2'";
	    break;
		case "0"://中评
	    return "buyimp='0'";
	    break;		
		case "-1"://差评
	    return "buyimp='-1'";
	    break;		
		case "append"://有追加
	    //return "buyimp='-1'";
	    break;		
		case "reply"://有回复
	    //return "buyimp='-1'";
	    break;		
		case "notauto"://非系统自评
	    //return "buyimp='-1'";
	    break;
	    default:
	    return "id!=''";
	}	
}
?>